//
//  ZZCTabBar.swift
//  weibo
//
//  Created by zhangzuchao on 17/3/26.
//  Copyright © 2017年 zhangZuChao. All rights reserved.
//

import UIKit

class ZZCTabBar: UITabBar {

    //按钮的懒加载
      lazy var composeButton: UIButton = {
      let button = UIButton()
        button.addTarget(self, action:#selector(composeButtonAction), for: .touchUpInside)
        //设置背景图片
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        
        //设置点击后图片
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        //根据内容设置大小
        button.sizeToFit()
        
        return button
    }()

    //定义闭包属性
    var didSelectedButton:  (()->())?
    
    //重写init方法,完成自定义的添加
    override init(frame: CGRect){
    super.init(frame: frame)
        setupUI()
    
    }
    //自动纠错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupUI () {
    
        //设置背景
        self.backgroundImage = UIImage(named: "tabbar_background")
        
        //添加自定义按钮
        addSubview(composeButton)
    }

    //闭包的执行
    func composeButtonAction(){
        
        //执行,等待主控制器回调
        didSelectedButton?()
    }

    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //设置中心
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
        //计算按钮宽度
        let itemWidth: CGFloat = width / 5
        
        var index = 0
        
        for subview in subviews{
            if subview.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                subview.width = itemWidth
                subview.x = CGFloat(index) * itemWidth
                index += 1
                if index == 2 {
                    index += 1
                }
            }
        }
    }
}






















